<template>
    <div>
        <div :id="id" :style="{ width: width + 'px', height: height + 'px' }"></div>
        <div class="title">{{ title }}</div>
    </div>
</template>
  
<script setup name="Pie">
import * as echarts from "echarts";
import useSettingsStore from '@/store/modules/settings'
const settingsStore = useSettingsStore()
// 主题颜色
const theme = computed(() => settingsStore.theme);

const props = defineProps({
    id: {
        default: ''
    },
    value: {
        default: 0,
        type: Number
    },
    width: {
        default: 200,
        type: Number
    },
    height: {
        default: 200,
        type: Number
    },
    title: {
        default: '',
        type: String
    }
})

let chart = null

watch(() => {
    return props.value;
}, (newValue, oldValue) => {
    if (chart) {
        chart.setOption({
            title: {
                text: newValue + '%',
            },
            series: [{
                data: [
                    { value: newValue, name: 'A', selected: true, itemStyle: { color: theme.value } },
                    { value: 100 - newValue, name: 'B', itemStyle: { color: '#ccc' } },
                ]
            }]
        })
    } else {
        initChart()
    }
}, { immediate: true, deep: true });


onMounted(() => {
    nextTick(() => {
        initChart()
    })
})

const width = ref(props.width)
const height = ref(props.height)

function initChart() {
    let dom = document.getElementById(props.id)
    if (!dom) return
    chart = echarts.init(document.getElementById(props.id), "purple-passion");
    chart.setOption({
        title: {
            text: props.value + '%',
            left: 'center',
            top: 'center',
            fontSize: 18,
        },
        series: [
            {
                name: '',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: true,
                label: {
                    show: false,
                    position: 'center'
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: props.value, name: 'A', itemStyle: { color: theme.value } },
                    { value: 100 - props.value, name: 'B', itemStyle: { color: '#ccc' } },
                ]
            }
        ]
    });
    chart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0, // 图表中的第一个系列
        dataIndex: 0, // 要高亮的数据项的索引
    });
    window.onresize = function () {
        chart.resize();
    };
}


</script>
  
<style scoped lang="scss">
.title {
    text-align: center;
}
</style>
  
  